package com.longsunhd.yum.buffalo.util;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.gg.reader.api.dal.GClient;
import com.gg.reader.api.dal.HandlerGpiOver;
import com.gg.reader.api.dal.HandlerGpiStart;
import com.gg.reader.api.dal.HandlerTag6bLog;
import com.gg.reader.api.dal.HandlerTag6bOver;
import com.gg.reader.api.dal.HandlerTagEpcLog;
import com.gg.reader.api.dal.HandlerTagEpcOver;
import com.gg.reader.api.dal.HandlerTagGbLog;
import com.gg.reader.api.dal.HandlerTagGbOver;
import com.gg.reader.api.protocol.gx.EnumG;
import com.gg.reader.api.protocol.gx.LogAppGpiOver;
import com.gg.reader.api.protocol.gx.LogAppGpiStart;
import com.gg.reader.api.protocol.gx.LogBase6bInfo;
import com.gg.reader.api.protocol.gx.LogBase6bOver;
import com.gg.reader.api.protocol.gx.LogBaseEpcInfo;
import com.gg.reader.api.protocol.gx.LogBaseEpcOver;
import com.gg.reader.api.protocol.gx.LogBaseGbInfo;
import com.gg.reader.api.protocol.gx.LogBaseGbOver;
import com.gg.reader.api.protocol.gx.MsgBaseInventory6b;
import com.gg.reader.api.protocol.gx.MsgBaseInventoryEpc;
import com.gg.reader.api.protocol.gx.MsgBaseInventoryGb;
import com.gg.reader.api.protocol.gx.MsgBaseStop;
import com.gg.reader.api.protocol.gx.Param6bReadUserdata;
import com.gg.reader.api.protocol.gx.ParamEpcReadReserved;
import com.gg.reader.api.protocol.gx.ParamEpcReadTid;
import com.gg.reader.api.protocol.gx.ParamEpcReadUserdata;
import com.gg.reader.api.protocol.gx.ParamGbReadUserdata;
import com.gg.reader.api.utils.ThreadPoolUtils;
import com.hks.power.HksPower;
import com.longsunhd.yum.buffalo.R;
import com.longsunhd.yum.buffalo.adapter.RecycleViewAdapter;
import com.longsunhd.yum.buffalo.entity.TagInfo;
import com.longsunhd.yum.buffalo.eventbus.EpcInfoEvent;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * 作者：黄宣淇
 * 时间：2021/5/11 0011
 * 如何代码没有备注，一个月后，只有你和上帝知道--鲁迅
 */
public class RfidReaderUtls {
    public  class MyActivity extends Activity{
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (isClient) {
                GlobalClient.getClient().close();
            }
            HksPower.uhf_power(0);
            unregisterReceiver(screenStatusReceiver);
            if (isClient) {
                if (isReader) {
                    MsgBaseStop msgStop = new MsgBaseStop();
                    client.sendSynMsg(msgStop);
                    if (msgStop.getRtCode() == 0) {
                        ToastUtils.showText("已停止读卡");
                    } else {
                        ToastUtils.showText(msgStop.getRtMsg());
                    }
                }
            }
        }
        @Override
        protected void onStop() {
            super.onStop();
            if (isClient) {
                if (isReader) {
                    MsgBaseStop msgStop = new MsgBaseStop();
                    client.sendSynMsg(msgStop);
                    if (msgStop.getRtCode() == 0) {
                        ToastUtils.showText("已停止读卡");
                    } else {
                        ToastUtils.showText(msgStop.getRtMsg());
                    }
                }
                isReader = false;
            }
        }

    }
    Activity mActivity;
    private static RfidReaderUtls rfidReaderUtls;
    public static   RfidReaderUtls newInstance( ){
        if(rfidReaderUtls==null){
            rfidReaderUtls=new RfidReaderUtls();

        }
        return  rfidReaderUtls;
    }

    private  ScreenStatusReceiver screenStatusReceiver;
    private  boolean isClient = false;



    private  GClient client = GlobalClient.getClient();
    private Map<String, TagInfo> tagInfoMap = new LinkedHashMap<String, TagInfo>();//去重数据源
    private List<TagInfo> tagInfoList = new ArrayList<TagInfo>();//适配器所需数据源
    private Long index = 1l;//索引
    private ParamEpcReadTid tidParam = null;
    private ParamEpcReadUserdata userParam = null;
    private ParamEpcReadReserved reserveParam = null;
    private Param6bReadUserdata user6bParam = null;
    private boolean[] isChecked = new boolean[]{false, false, false};//标识读0-epc与1-user
    private Handler mHandler = new Handler();
    private Runnable r = null;
    private Runnable timeTask = null;
    private int time = 0;
    private boolean isReader = false;
    private SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    private int port = 13;
    private int baudrate = 115200;
    private boolean isSound = true;
    MenuItem gMenuItem = null;
    private boolean isSensor = false;

    static class ScreenStatusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
                HksPower.uhf_power(1);
            } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
                HksPower.uhf_power(0);
            }
        }
    }

    public  void init(Activity activity){
        mActivity=activity;
        initAndroidPorts();

        screenStatusReceiver = new ScreenStatusReceiver();
        IntentFilter screenStatusIF = new IntentFilter();
        screenStatusIF.addAction(Intent.ACTION_SCREEN_ON);
        screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF);
        mActivity. registerReceiver(screenStatusReceiver, screenStatusIF);



        if (isClient) {
            subHandler(GlobalClient.getClient());
        }
        UtilSound.initSoundPool(activity);
    }

    //初始化连接
    private  void initAndroidPorts() {
        String hks = "/dev/ttysWK0:115200";
        HksPower.uhf_power(1);
        if (GlobalClient.getClient().openAndroidSerial(hks, 1000)) {
            isClient = true;
            ToastUtils.showText("连接成功");
        } else {
            isClient = false;
            ToastUtils.showText("连接失败");
        }
    }





    //去重6B
    public Map<String, TagInfo> pooled6bData(LogBase6bInfo info) {
        if (tagInfoMap.containsKey(info.getTid())) {
            TagInfo tagInfo = tagInfoMap.get(info.getTid());
            Long count = tagInfoMap.get(info.getTid()).getCount();
            count++;
            tagInfo.setRssi(info.getRssi() + "");
            tagInfo.setCount(count);
            tagInfoMap.put(info.getTid(), tagInfo);
        } else {
            TagInfo tag = new TagInfo();
            tag.setIndex(index);
            tag.setType("6B");
            tag.setCount(1l);
            tag.setUserData(info.getUserdata());
            if (info.getTid() != null) {
                tag.setTid(info.getTid());
            }
            tag.setRssi(info.getRssi() + "");
            tagInfoMap.put(info.getTid(), tag);
            index++;
        }
        handlerStop.sendEmptyMessage(2);
        return tagInfoMap;
    }
    //去重6C
    public Map<String, TagInfo> pooled6cData(LogBaseEpcInfo info) {
        if (tagInfoMap.containsKey(info.getTid() + info.getEpc())) {
            TagInfo tagInfo = tagInfoMap.get(info.getTid() + info.getEpc());
            Long count = tagInfoMap.get(info.getTid() + info.getEpc()).getCount();
            count++;
            tagInfo.setRssi(info.getRssi() + "");
            tagInfo.setReservedData(info.getReserved());
            tagInfo.setUserData(info.getUserdata());
//            if (isSensor)
//                if (info.getReserved() != null && !info.getReserved().equals("0000")) {
//                    tagInfo.setNmv2d(computedNmv2d(info.getUserdata(), info.getReserved()));
//                } else {
////                    tagInfo.setNmv2d(null);
//                }
            tagInfo.setCount(count);
            tagInfoMap.put(info.getTid() + info.getEpc(), tagInfo);
        } else {
            TagInfo tag = new TagInfo();
            tag.setIndex(index);
            tag.setType("6C");
            tag.setEpc(info.getEpc());
            tag.setCount(1l);
            tag.setUserData(info.getUserdata());
            tag.setReservedData(info.getReserved());
//            if (isSensor)
//                if (info.getReserved() != null && !info.getReserved().equals("0000")) {
//                    tag.setNmv2d(computedNmv2d(info.getUserdata(), info.getReserved()));
//                } else {
////                    tag.setNmv2d(null);
//                }
            tag.setTid(info.getTid());
            tag.setRssi(info.getRssi() + "");
            tagInfoMap.put(info.getTid() + info.getEpc(), tag);
            index++;
        }
        handlerStop.sendEmptyMessage(2);
        return tagInfoMap;
    }

    //去重GB
    public Map<String, TagInfo> pooledGbData(LogBaseGbInfo info) {
        if (tagInfoMap.containsKey(info.getTid() + info.getEpc())) {
            TagInfo tagInfo = tagInfoMap.get(info.getTid() + info.getEpc());
            Long count = tagInfoMap.get(info.getTid() + info.getEpc()).getCount();
            count++;
            tagInfo.setRssi(info.getRssi() + "");
            tagInfo.setCount(count);
            tagInfoMap.put(info.getTid() + info.getEpc(), tagInfo);
        } else {
            TagInfo tag = new TagInfo();
            tag.setIndex(index);
            tag.setType("GB");
            tag.setEpc(info.getEpc());
            tag.setCount(1l);
            tag.setUserData(info.getUserdata());
            tag.setTid(info.getTid());
            tag.setRssi(info.getRssi() + "");
            tagInfoMap.put(info.getTid() + info.getEpc(), tag);
            index++;
        }
        handlerStop.sendEmptyMessage(2);
        return tagInfoMap;
    }

    public String computedNmv2d(String userHex, String reservedHex) {
        String symbol = userHex.substring(0, 2);
        String value = userHex.substring(2, 4);
        int tune = 0;
        if (symbol.indexOf("1") != -1) {
            tune = Integer.parseInt((symbol + Integer.parseInt(value, 16)));
        } else {
            tune = Integer.parseInt(value, 16);
        }
        int n = Integer.parseInt(reservedHex.substring(1, 4), 16);
        double v = (n + tune - 500) / 5.4817 + 24.9;
        return String.format("%.2f", v) + "℃";
    }

    final Handler handlerStop = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mHandler.removeCallbacks(r);
                    mHandler.removeCallbacks(timeTask);
                    upDataPane();
                    isReader = false;
                    break;
                case 2:
                    ThreadPoolUtils.run(new Runnable() {
                        @Override
                        public void run() {
                            if (isSound)
                                UtilSound.play(1, 0);
                        }
                    });

                    break;
            }
            super.handleMessage(msg);
        }
    };
    //更新面板
    private void upDataPane() {

       /* readCount.setText(getReadCount(tagInfoList) + "");
        tagCount.setText(tagInfoList.size() + "");*/
    }

    //获取读取总次数
    private long getReadCount(List<TagInfo> tagInfoList) {
        long readCount = 0;
        for (int i = 0; i < tagInfoList.size(); i++) {
            readCount += tagInfoList.get(i).getCount();
        }
        return readCount;
    }
    public  static final int C6=1;
    public  static final int B6=2;
    public  static final int GB=3;
    
    public static final int sinal=4;
    public static final int repeat=5;
    public void readCard(int type,int repeatType) {
        if (isClient) {
            if (!isReader) {
                if (type== C6) {
                    /*6c*/
                    MsgBaseInventoryEpc msg = new MsgBaseInventoryEpc();
                    msg.setAntennaEnable(EnumG.AntennaNo_1);
                    if (repeatType==sinal) {
                        msg.setInventoryMode(EnumG.InventoryMode_Single);
                    } else {
                        msg.setInventoryMode(EnumG.InventoryMode_Inventory);
                    }
                    if (isChecked[0]) {
                        tidParam = new ParamEpcReadTid();
                        tidParam.setMode(EnumG.ParamTidMode_Auto);
                        tidParam.setLen(6);
                        msg.setReadTid(tidParam);
                    }
                    if (isChecked[1]) {
                        userParam = new ParamEpcReadUserdata();
                        userParam.setStart(0);
                        userParam.setLen(6);
                        msg.setReadUserdata(userParam);
                    }
                    if (isChecked[2]) {
                        reserveParam = new ParamEpcReadReserved();
                        reserveParam.setStart(0);
                        reserveParam.setLen(4);
                        msg.setReadReserved(reserveParam);
                    }

                    client.sendSynMsg(msg);
                     
                    computedSpeed();
                    if (0x00 == msg.getRtCode()) {
                        ToastUtils.showText("开始读卡");
                        isReader = true;
                    } else {
                        handlerStop.sendEmptyMessage(1);
                        ToastUtils.showText(msg.getRtMsg());
                    }
                } else if (type==B6) {
                    /*6B*/
                    MsgBaseInventory6b msg = new MsgBaseInventory6b();
                    msg.setAntennaEnable(EnumG.AntennaNo_1);
                    if (repeatType==sinal) {
                        msg.setInventoryMode(EnumG.InventoryMode_Single);
                    } else {
                        msg.setInventoryMode(EnumG.InventoryMode_Inventory);
                    }
                    if (isChecked[1]) {
                        user6bParam = new Param6bReadUserdata();
                        user6bParam.setStart(0);
                        user6bParam.setLen(10);
                        msg.setReadUserdata(user6bParam);
                    }
                    msg.setArea(EnumG.ReadMode6b_Tid);

                    client.sendSynMsg(msg);
                     
                    computedSpeed();
                    if (0x00 == msg.getRtCode()) {
                        ToastUtils.showText("开始读卡");
                        isReader = true;
                    } else {
                        handlerStop.sendEmptyMessage(1);
                        ToastUtils.showText(msg.getRtMsg());
                    }
                } else if (type==GB) {
                    /*GB*/
                    MsgBaseInventoryGb msg = new MsgBaseInventoryGb();
                    msg.setAntennaEnable(EnumG.AntennaNo_1);
                    if (repeatType==sinal) {
                        msg.setInventoryMode(EnumG.InventoryMode_Single);
                    } else {
                        msg.setInventoryMode(EnumG.InventoryMode_Inventory);
                    }
                    if (isChecked[0]) {
                        ParamEpcReadTid tid = new ParamEpcReadTid();
                        tid.setMode(EnumG.ParamTidMode_Auto);
                        tid.setLen(6);
                        msg.setReadTid(tid);
                    }
                    if (isChecked[1]) {
                        ParamGbReadUserdata gbReadUserdata = new ParamGbReadUserdata();
                        gbReadUserdata.setStart(4);//字
                        gbReadUserdata.setLen(1);//字
                        gbReadUserdata.setChildArea(0x30);
                        msg.setReadUserdata(gbReadUserdata);
                    }

                    client.sendSynMsg(msg);
                     
                    computedSpeed();
                    if (0x00 == msg.getRtCode()) {
                        ToastUtils.showText("开始读卡");
                        isReader = true;
                        System.out.println("MsgBaseInventoryGB[OK].");
                    } else {
                        handlerStop.sendEmptyMessage(1);
                        ToastUtils.showText(msg.getRtMsg());
                    }
                }

                isSensor = false;
            } else {
                ToastUtils.showText("请先停止读卡");
            }
        } else {
            ToastUtils.showText("未连接");
        }
    }
    //订阅
    public void subHandler(GClient client) {
        client.onTagEpcLog = new HandlerTagEpcLog() {
            public void log(String readerName, LogBaseEpcInfo info) {
                if (null != info && 0 == info.getResult()) {
                    mActivity. runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Map<String, TagInfo> infoMap = pooled6cData(info);
                            /*結果*/
                            EpcInfoEvent epcInfoEvent=  new EpcInfoEvent();epcInfoEvent.setLogBaseEpcInfo(info);
                            EventBus.getDefault().post(epcInfoEvent);
                            info.getEpc();
                            tagInfoList.clear();
                            tagInfoList.addAll(infoMap.values());
                            Log.i("Read",infoMap.values()+"");
                        }
                    });
                }
            }
        };
        client.onTagEpcOver = new HandlerTagEpcOver() {
            public void log(String readerName, LogBaseEpcOver info) {
                handlerStop.sendEmptyMessage(1);
            }
        };
        client.onTag6bLog = new HandlerTag6bLog() {
            public void log(String readerName, LogBase6bInfo info) {
                if (null != info && info.getResult() == 0) {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Map<String, TagInfo> infoMap = pooled6bData(info);
                            tagInfoList.clear();
                            tagInfoList.addAll(infoMap.values());
                        }
                    });
                }
            }
        };
        client.onTag6bOver = new HandlerTag6bOver() {
            public void log(String readerName, LogBase6bOver info) {
                handlerStop.sendEmptyMessage(1);
            }
        };
        client.onTagGbLog = new HandlerTagGbLog() {
            public void log(String readerName, LogBaseGbInfo info) {
                if (null != info && info.getResult() == 0) {
                    mActivity. runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Map<String, TagInfo> infoMap = pooledGbData(info);
                            tagInfoList.clear();
                            tagInfoList.addAll(infoMap.values());
                        }
                    });
                }

            }
        };
        client.onTagGbOver = new HandlerTagGbOver() {
            public void log(String readerName, LogBaseGbOver info) {
                handlerStop.sendEmptyMessage(1);
            }
        };
        client.onGpiOver = new HandlerGpiOver() {
            @Override
            public void log(String s, LogAppGpiOver logAppGpiOver) {
                System.out.println(logAppGpiOver);
            }
        };
        client.onGpiStart = new HandlerGpiStart() {
            @Override
            public void log(String s, LogAppGpiStart logAppGpiStart) {
                System.out.println(logAppGpiStart);
            }
        };
    }
    //格式化时间
    public String secToTime(long time) {
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        time = time * 1000;
        String hms = formatter.format(time);
        return hms;
    }
    //一秒刷新计算
    private void computedSpeed() {
        Map<String, Long> rateMap = new Hashtable<String, Long>();
        r = new Runnable() {
            @Override
            public void run() {
                String toTime = secToTime(++time);
               // timeCount.setText(toTime + " (s)");
                long before = 0;
                long after = 0;
                Long afterValue = rateMap.get("after");
                if (null != afterValue) {
                    before = afterValue;
                }
               // readCount.setText(getReadCount(tagInfoList) + "");
              //  tagCount.setText(tagInfoList.size() + "");
                rateMap.put("after", Long.valueOf(getReadCount(tagInfoList) + ""));
                after = Long.valueOf(getReadCount(tagInfoList) + "");
                if (after >= before) {
                    long rateValue = after - before;
                  //  speed.setText(rateValue + " (t/s)");
                }
                //每隔1s循环执行run方法
                mHandler.postDelayed(this, 1000);
            }
        };
        //延迟一秒执行
        mHandler.postDelayed(r, 1000);
    }

}
